<template>
  <el-dialog
    :width="600"
    destroy-on-close
    draggable
    title="Import File"
    v-model="dialogUploadFileFormVisible"
  >
    <div class="step-container">
      <div class="step-item">
        <span>Step 1</span>
        <!-- <span>{{$t("ship.common.downloadDecs")}}</span> -->
        <div v-if="isDownTemplate">
          <el-button
          type="primary"
            @click="downTemplate"
          >
            {{ $t("ship.button.downloadTemplate") }}</el-button
          >
        </div>
      </div>
      <div class="step-item step2-item">
        <span>Step 2</span>
        <!-- <span>{{$t("ship.common.uploadDecs")}}</span> -->
        <el-upload
          multiple
          :action="props.uploadFileUrl"
          :before-upload="handleBeforeUpload"
          :file-list="fileList"
          :limit="limit"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          :on-success="handleUploadSuccess"
          :show-file-list="false"
          :headers="headers"
          class="upload-file-uploader"
          :accept="props.fileType.join(',')"
          ref="fileUpload"
          :data="uploadData"
          style="display: inline-block"
        >
          <!-- 上传按钮 -->
          <el-button type="primary">Import</el-button>
        </el-upload>
      </div>
    </div>

    <!-- 下载模板按钮 -->

    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      Please upload File
      <template v-if="fileSize">
        Not more than <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        The file format is
        <b style="color: #f56c6c">{{ getTypeStr(fileType) }}</b>
      </template>
    </div>
    <!-- 文件列表 -->
    <transition-group
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul"
    >
      <li
        :key="file.uid"
        class="el-upload-list__item ele-upload-list__item-content"
        v-for="(file, index) in fileList"
      >
        <el-link :href="file.url" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger"
            >删除</el-link
          >
        </div>
      </li>
    </transition-group>
  </el-dialog>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import { downloadFile } from "@/utils/downloadFile";
const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 1,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => [".doc", ".xls", ".ppt", ".txt", ".pdf"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true,
  },
  isAlink: {
    type: Boolean,
    default: true,
  },
  isDownTemplate: {
    type: Boolean,
    default: true,
  },
  uploadFileUrl: {
    type: String,
    default: "",
  },
  queryParams: {
    type: Object,
    default: () => {
      return {};
    },
  },
  uploadData: {
    type: Object,
    default: () => {
      return {};
    },
  },
  templateFile: {
    type: String,
    default: "Template.xlsx",
  },
  url: {
    type: String,
    default:
      "https://booking-1257832417.cos.ap-nanjing.myqcloud.com/template/vehicleTemplate.xlsx",
  },
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const baseUrl = import.meta.env.VITE_APP_BASEURL;
//const uploadFileUrl = ref(baseUrl + "/file/upload"); // 上传文件服务器地址
const headers = ref({ authentication: getToken() });
const fileList = ref([]);
const dialogUploadFileFormVisible = ref(false);
const dialogUploadFileForm = () => {
  dialogUploadFileFormVisible.value = true;
};
defineExpose({ dialogUploadFileForm });
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      let temp = 1;
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : props.modelValue.split(",");
      // 然后将数组转为对象数组
      fileList.value = list.map((item) => {
        if (typeof item === "string") {
          item = { name: item, url: item };
        }
        item.uid = item.uid || new Date().getTime() + temp++;
        return item;
      });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split(".");
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf("." + fileExt) >= 0;
    if (!isTypeOk) {
      proxy.$modal.msgError(
        `The file format is incorrect, please upload it ${getTypeStr(
          props.fileType
        )} Format file!`
      );
      return false;
    }
  }
  // 校检文件名是否包含特殊字符
  if (file.name.includes(",")) {
    proxy.$modal.msgError(
      "The file name is incorrect and cannot contain English commas!"
    );
    return false;
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(
        `The size of the uploaded file cannot exceed ${props.fileSize} MB!`
      );
      return false;
    }
  }
  
  // 阻止自动上传，使用Promise来处理二次确认
  const uploadPromise = new Promise((resolve, reject) => {
    proxy.$modal.confirm(`Confirm to upload the file "${file.name}" ？`, 'confirm', {
      confirmButtonText: 'confirm',
      cancelButtonText: 'cancel',
      type: 'warning'
    }).then(() => {
      proxy.$modal.loading("Uploading files, please wait...");
      number.value++;
      resolve(true);
    }).catch(() => {
      reject(false);
    });
  });
  
  return uploadPromise;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(err) {
  // proxy.$modal.msgError("上传文件失败");
  proxy.$modal.msgError("upload file failed");
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    uploadList.value.push({ name: res.data.url, url: res.data.url });
    dialogUploadFileFormVisible.value = false;
    if (res.msg) {
      proxy.$modal.msgSuccess(res.msg);
    }
    uploadedSuccessfully();
  }
  if (res.code === 0) {
    uploadList.value = res.data || [];
    dialogUploadFileFormVisible.value = false;
    if (res.msg) {
      proxy.$modal.msgSuccess(res.msg);
    }
    uploadedSuccessfully();
  } else {
    number.value--;
    proxy.$modal.msgError(res.message || res.data);
    proxy.$refs.fileUpload.handleRemove(file);
    proxy.$modal.closeLoading();
    setTimeout(() => {
      dialogUploadFileFormVisible.value = false;
    }, 5000);
  }
}

// 删除文件
function handleDelete(index) {
  fileList.value.splice(index, 1);
  emit("update:modelValue", listToString(fileList.value));
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value?.length === number.value) {
    fileList.value = fileList.value
      .filter((f) => f.url !== undefined)
      .concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    emit("update:modelValue", listToString(fileList.value));
    proxy.$modal.closeLoading();
    fileList.value = [];
  } else {
    emit("update:modelValue", listToString(fileList.value));
    proxy.$modal.closeLoading();
  }
}

// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}

// 获取文件名称
function getTypeStr(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (list[i]) {
      strs += list[i].split(".").pop() + separator;
    }
  }
  return strs != "" ? strs.substr(0, strs.length - 1) : "";
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url + separator;
    }
  }
  return strs != "" ? strs.substr(0, strs.length - 1) : "";
}
const downTemplate = () => {
  downloadFile(props.url, props.queryParams, props.templateFile);
};
</script>

<style scoped lang="scss">

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
.step-container{
  display: flex;
  margin-bottom: 20px;
  .step-item {
    position: relative;
    margin-right: 10px;
    padding:7px 10px;
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 5px;
    border: 1px solid #e4e7ed;
    border-right: none;
     color: #000;
    span:first-child {
      flex-shrink: 1;
     width: 80px;
      font-weight: bold;
    }
  }
  .step-item::after {
      content: "";
    position: absolute;
    bottom: 18px;
    left: 99%;
    transform: translateX(-50%);
    width: 35px;
    height: 36px;
    border-right: 1px solid #e4e7ed;
    border-bottom: 1px solid #e4e7ed;
    transform: rotate(-45deg) translateX(-50%);
  }
   .step2-item{
    border-left: none;
    margin-right: 40px;
    box-sizing: border-box;
    box-sizing: border-box;
    span:nth-child(1) {
      margin-left: 20px;
      width: 50px;
    }
    span:nth-child(2) {
      margin-right: 40px;
    }
    
   }
  .step2-item::before {
      content: "";
    position: absolute;
    bottom: 18px;
    left: -1%;
    transform: translateX(-50%);
    width: 35px;
    height: 36px;
    border-right: 1px solid #e4e7ed;
    border-bottom: 1px solid #e4e7ed;
    transform: rotate(-45deg) translateX(-50%);
  }
}
</style>
